package server.processors;

import java.nio.channels.ClosedChannelException;

import server.NetworkMediator;
import server.ServerStateMediator;

import common.Player;
import common.ReadyPacket;
import common.Round;
import common.Sendable;

public class ReadyProcessor extends Processor {

	public ReadyProcessor() {}
	
	public ReadyProcessor( NetworkMediator mediator, ServerStateMediator server) {
		super( mediator, server );
	}
	
	public Processor getInstanceOf(NetworkMediator mediator,
			ServerStateMediator server) {
		return new ReadyProcessor( mediator, server);
	}

	
	public boolean isInterestedIn(Sendable s) {
		return s instanceof ReadyPacket;
	}

	public void run() {
		ServerStateMediator server = getServer();
		
		Player sender = server.sentBy();
		
		Round round = sender.getRound();
		
		ReadyPacket msg = (ReadyPacket) server.getMessage();
		
		//Make sure the player is in a round and the ready up message is appropriate
		if( round != null && sender.getName().equals( msg.whoIsReady ) ) {
			boolean previousReady = sender.isReady();
			sender.setIsReady( msg.ready );
			
			
			try {
				if( previousReady != msg.ready )
					getNetwork().sendToAllInRound( round, msg );
			} catch (ClosedChannelException e) {
				System.err.println("Unable to send the readyMessage to clients.");
			}
		}
	}

}
